﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace QLTK
{
    internal class Database
    {
        private readonly SqlConnection _connect;

        private readonly string _connstr;

        protected internal Database()
        {
            _connstr = ConfigurationManager.ConnectionStrings["QLTK.Properties.Settings.QLTKConnection"].ToString();

            _connect = new SqlConnection(_connstr);
            //connect = new SqlConnection("Data Source=" + _server + ";Initial Catalog=" + _database + ";User Id=" + _username + ";Password=" + _password);
        }

        public SqlConnection CheckConnect()
        {
            try
            {
                if (_connect.State == ConnectionState.Closed || _connect.State == ConnectionState.Broken)
                {
                    _connect.Open();
                    MessageBox.Show("Kết nối thành công!", "QLTK");
                }
            }
            catch
            {
                MessageBox.Show("Kết nối không thành công, kiểm tra lại cấu hình", "QLTK");
            }
            return _connect;
        }

        public SqlConnection OpenConnect()
        {
            try
            {
                if (_connect.State == ConnectionState.Closed || _connect.State == ConnectionState.Broken)
                {
                    _connect.Open();
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show("Kết nối không thành công, kiểm tra lại cấu hình", "QLTK");
                MessageBox.Show(e.ToString(), "QLTK");
            }
            return _connect;
        }

        public SqlConnection CloseConnect()
        {
            try
            {
                if (_connect.State == ConnectionState.Open)
                {
                    _connect.Close();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi khi đóng kết nối");
                throw;
            }
            return _connect;
        }
    }
}